﻿/*
# Copyright (c) 2010, Alexander Chaiko, All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 
# * Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*/


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using HtmlAgilityPack;

namespace libvkontakte
{
    public class API
    {  
        /// <summary>
        /// Парсим html код и ищем сообщение об ошибке.
        /// </summary>
        /// <param name="html">html в котором ищется сообщение об ошибке</param>
        /// <returns></returns>
        private static bool IsError(string html)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            var error = doc.DocumentNode.SelectNodes("//div[@id=\"error\"]");
            if (error != null) return false;
            return true;
        }

        public static bool IsLogin(HttpWebResponse response)
        {
            return IsError(Connection.ReadResponse(response));
        }

        public static bool IsLogout(HttpWebResponse response)
        {
            Uri url = new Uri(PagesUrls.MainPageUrl);
            if(url.Equals(response))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Парсим страницу на предмет блоков с новыми сообщениями.
        /// </summary>
        /// <param name="html">html страницы с сообщениями</param>
        /// <returns></returns>
        public static List<Dictionary<string,string>> ParseMessagesPage(string html)
        {
            var results = new List<Dictionary<string,string>>();
            
            var doc = new HtmlDocument();   
            doc.LoadHtml(html);

            var messages = doc.DocumentNode.SelectNodes("//div[@class=\"newMsg\"]");

            if (messages == null) return results;

            #region parsing process

            foreach (HtmlNode message in messages)
            {
                var tempNodeResult = new Dictionary<string, string>();
                var minidoc = new HtmlDocument();
                minidoc.LoadHtml(message.InnerHtml);
                var msgBlock = minidoc.DocumentNode.SelectNodes("//a[@href]");
                
                tempNodeResult["MessageLink"] = msgBlock[0].Attributes[0].Value; // магические числа =\
                tempNodeResult["DeleteLink"] = msgBlock[1].Attributes[0].Value;
                
                string temp = msgBlock[0].InnerText;
                var res = temp.Split('\n');
                tempNodeResult["From"] = res[0];
                tempNodeResult["MsgPreview"] = res[2].Trim();
                results.Add(tempNodeResult);
            }

            #endregion

            return results;
        }

        /// <summary>
        /// Получаем циферки стоящие в меню напротив всех пунктиков.
        /// </summary>
        /// <example>Сообщения(2)
        ///          Друзья(1)
        ///          Встречи(2)
        ///          и тд.
        /// </example>
        /// <param name="html"></param>
        /// <returns></returns>
        public static Dictionary<string,int> GetBarIndexes(string html)
        {
            var indexesDict = new Dictionary<string, int>();
            var namesBarIndexes = new List<string>();

            #region enumeration indexes
            namesBarIndexes.Add("mypage");
            namesBarIndexes.Add("Friends");
            namesBarIndexes.Add("Photos");
            namesBarIndexes.Add("Messages");
            namesBarIndexes.Add("Bookmarks");
            namesBarIndexes.Add("News");
            namesBarIndexes.Add("Notes");
            namesBarIndexes.Add("Groups");
            namesBarIndexes.Add("Events");
            namesBarIndexes.Add("Opinions");
            namesBarIndexes.Add("settings");
            namesBarIndexes.Add("exit");
            namesBarIndexes.Add("some");
            #endregion

            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var menu2 = doc.DocumentNode.SelectNodes("//div[@class=\"menu2\"]");
            var minidoc = new HtmlDocument();
            minidoc.LoadHtml(menu2[0].InnerHtml);
            Regex newreg = new Regex("[0-9]");

            int counter = 0;
            foreach (var item in minidoc.DocumentNode.SelectNodes("//div"))
            {
                var index = item.InnerText;
                var m = newreg.Match(index);
                int indexValue = 0;
                if (m.Success) indexValue = int.Parse(m.Value);
                indexesDict.Add(namesBarIndexes[counter],indexValue);
                counter++;
            }
            return indexesDict;
        }
    }
}
